/**
 * 基础信息传入后，利用jsdom修改html文件
 */
import jsdom from 'jsdom';
import path from 'path';
import fse from 'fs-extra';
import ejs from 'ejs';
import dirinfo from './dirinfo.js';

const { JSDOM } = jsdom;
const { writeFileSync, copySync } = fse;
const { renderFile } = ejs;
const { __dirname } = dirinfo;

export default async ({ payload, distDir }) => {
  const manifest = await renderFile(
    path.resolve(__dirname, './template/manifest.json'),
    {
      title: payload.title,
    }
  );
  const dom = new JSDOM(payload.html);
  const document = dom.window.document;
  const metaNode = document.createElement('link');
  metaNode.setAttribute('rel', 'manifest');
  metaNode.setAttribute('href', './manifest.json');
  document.head.appendChild(metaNode);
  const scriptNode = document.createElement('script');
  scriptNode.innerHTML = `
    if ("serviceWorker" in navigator) {
      if (navigator.serviceWorker.controller) {
        console.log("[PWA Builder] active service worker found, no need to register");
      } else {
        // Register the service worker
        navigator.serviceWorker
          .register("./pwabuilder-sw.js", {
            scope: "./"
          })
          .then(function (reg) {
            console.log("[PWA Builder] Service worker has been registered for scope: " + reg.scope);
          });
      }
    }
  `;
  document.head.appendChild(scriptNode);
  payload.html = dom.serialize();
  copySync(path.resolve(__dirname, './template/'), distDir);
  writeFileSync(path.resolve(distDir, 'manifest.json'), manifest);
};
